import React, { useEffect, useRef, useImperativeHandle } from 'react';
import { Table } from '@maycur/antd5';
import { Resizable } from 'react-resizable';
import classname from 'classnames';
import getTableProps from './lib/getTableProps';
import useHandleScroll from './hooks/useHandleScroll';
import useGenColumns from './hooks/useGenColumns';
import useHandleChange from './hooks/useHandleChange';
import usePagination from './hooks/usePagination';
import Pagination from './Pagination';
import ToolBar from './ToolBar';
import debugMan from './lib/debugMan';
import './table.less';

debugMan.setDebug(false);

const ResizeableTitle = props => {
    const { onResize, width, ...restProps } = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};


/**
* * 开发日志
* * 1. 支持高度和宽度固定
* * 2. 支持container层的自适应高宽度（默认）
* ? width是否有支持自适应的必要? - 不支持
* * 3. 自定义Filter通用接口
* * 4. 列冻结，左右多列冻结实现
* * 5. 后台获取数据，实现pagination
* * 6. 支持后台数据获取单页全选，跨页全选，单页反选
* * 7. 定义tableOnchange的出发接口
* * 8. 实现gulp打包机制（开发中-王）
*/
function McTable(props, ref) {
    const {
        headerFix, search, scrollWidth, scrollHeight, style, fetchData, columnSet, filterBar, resizable, prefixCls = 'ant',
    } = props;
    const { customToolBars } = props;
    const { filterDropdownMap } = filterBar || {};
    const containerRef = useRef(null);
    const wrapperCls = classname('mctable-wrapper', {
        fix: headerFix,
    });
    const containerCls = classname('mctable-container', {
        fix: headerFix,
    });
    const { pagination, updatePageInfo } = usePagination();
    const { filterState, handleChange, refreshTable, tableState, loading } = useHandleChange(fetchData, { pagination, loading: props.loading, updatePageInfo });
    const { columns, originColumns, addedColumns, removedColumns, updateColumnsDisplay } = useGenColumns(props.columns, { filterDropdownMap, tableState, columnSet, resizable });
    const scrollValue = useHandleScroll(headerFix, containerRef, { width: scrollWidth, height: scrollHeight, prefixCls });
    const components = resizable && {
        header: {
            cell: ResizeableTitle,
        },
    };
    useImperativeHandle(ref, () => ({
        refreshTable
    }));
    return (
        <div className={containerCls} style={style || {}} >
            <ToolBar
                hasFilterBar={!!filterBar}
                hasSearch={!!search}
                hasColumnSet={!!columnSet}
                filterState={filterState}
                columns={columns}
                pagination={pagination}
                originColumns={originColumns}
                columnSet={columnSet}
                tableState={tableState}
                addedColumns={addedColumns}
                removedColumns={removedColumns}
                refreshTable={refreshTable}
                updateColumnsDisplay={updateColumnsDisplay}
                customToolBars={customToolBars}
            />
            {// ! 重要，不要在table的wrapper容器中加入任何非table元素，会影响table中scroll高度的计算规则
            }
            <div className={wrapperCls} ref={containerRef}>
                <Table
                    {...getTableProps(props)}
                    columns={columns}
                    loading={loading}
                    pagination={pagination}
                    scroll={scrollValue}
                    components={components}
                    onChange={handleChange}
                    getPopupContainer={() => {
                        return containerRef?.current?.querySelector('.maycur-table-wrapper');
                    }}
                />
                <Pagination />
            </div>

        </div>
    );
}
const ForwardCom = React.forwardRef(McTable);
// * 处理props中的默认值，因为McTable被react.forwardRef导致后，被包裹的组件不在是react组件(代码层面)，所有defaultProps不生效
// * 所以实现defaultProps的效果，需要在包括后的组件中设置
ForwardCom.defaultProps = {
    headerFix: true,
    search: false,
    scrollWidth: 'max-content',
    prefixCls: 'ant',
    isSlimPagination: false,
}
export default ForwardCom; 